import {config} from '../config/config'

class IM {
    events = {}

    constructor() {
        if (typeof IM.instance === 'object') {
            return IM.instance
        }
        IM.instance = this
        return this
    }

    polling() {
        wx.request({
            url: config.apiBaseUrl + 'deferredResult/request1',
            headers: {},
            method: 'GET',
            data: {},
            timeout: 30000,
            dataType: '',
            success: (result) => {
                console.log(result)
                if (result.data === "新消息") {
                    this._publish('getMessage', result.data)
                }
                this.polling()
            },
            fail: () => {

            },
            complete: () => {

            }
        });
    }

    on(event, fn) {
        this.events.event = this.events.event || []
        this.events.event.push(fn)
    }

    off(event, fn) {
        const index = (this.events.event || []).indexOf(fn)
        if (index < -1) {
            return
        } else {
            this.events.event.splice(index, 1)
        }
    }

    _publish(event, data) {
        this.events.event.forEach(fn => fn(data))
    }
}

export {
    IM
};
